﻿@using SubstrateHelper.Models;
@using SubstrateHelper.Data;
@using ProcessBase.Models;
@using System.Collections.Concurrent;
@using System.Collections.Generic;
@using System.Linq;
@using System.Timers;
@using BootstrapBlazor.Components;


@inject SubstrateHelperDbContext Db
@inject MessageService MessageService
@inject AuthenticationStateProvider AuthenticationStateProvider
@inject UserManager<IdentityUser> UserManager
@inject NavigationManager NavigationManager
<div>
    

    @if (ProcessDetails != null && ProcessDetails.Count > 0)
    {
        <div>工站：<strong class="text-primary">@ProcessDetails[0].Parameter.ProcessName</strong> 【<strong class="text-primary">@ProcessDetails[0].RecordTitle</strong>】</div>
        <div class="mt-2">
            <table class="table table-striped table-bordered">
                <thead>
                    <tr style="height:3em">

                        <th align="center" width="150"><strong class="text-primary ml-2 mr-2">参数名</strong></th>
                        <th align="center"><strong class="text-primary ml-2 mr-2">参数值</strong></th>
                        <th align="center"><strong class="text-primary ml-2 mr-2">单位</strong></th>
                        <th align="center"><strong class="text-primary ml-2 mr-2">检验标准</strong></th>
                        <th align="center"><strong class="text-primary ml-2 mr-2">合格率(%)</strong></th>
                        <th align="center"><strong class="text-primary ml-2 mr-2">检验员</strong></th>
                        <th align="center"><strong class="text-primary ml-2 mr-2">质量状态</strong></th>
                    </tr>

                </thead>
                <tbody>

                    @foreach (var detail in ProcessDetails)
                    {

                        <tr style="height:3em">
                            @{
                                string css = "m-2 text-primary";
                                string star = "";
                                @if (detail.Parameter.IsCheckPoint)
                                {
                                    star = "【检】";
                                    if (detail.Record.QualityState == "报废")
                                    {
                                        css = "m-2 colorBaoFei";
                                    }
                                    else if (detail.Record.QualityState == "让步流通")
                                    {
                                        css = "m-2 colorRangBu";
                                    }
                                    else if (detail.Record.QualityState == "扣留")
                                    {
                                        css = "m-2 colorZanKou";
                                    }
                                    else if (detail.Record.QualityState == "正常流通")
                                    {
                                        css = "m-2 text-success";
                                    }
                                    else
                                    {
                                        css = "m-2 text-dark";
                                    }
                                }
                            }

                            <td><strong class="@css">@star  @detail.Parameter.ParameterName</strong></td>

                            @*参数值*@
                            <td>
                                <div class="m-2">
                                    @if (detail.Parameter.ParameterName == "来料标识" && InputLots != null)
                                    {
                                        if (string.IsNullOrWhiteSpace(detail.Record.StringValue))
                                        {
                                            detail.Record.StringValue = null;
                                        }

                                        <BootstrapInput @bind-Value="@detail.Record.StringValue" />

                                        @*if (_ValidateSelect(detail.Record.StringValue, InputLots, true))
                                        {
                                            <MultiSelect Color="Color.Success" Items="@InputLots" @bind-Value="@detail.Record.StringValue" @key="detail.Record.StringValue"></MultiSelect>
                                        }
                                        else
                                        {
                                            <BootstrapInput @bind-Value="@detail.Record.StringValue" />
                                        }*@

                                    }
                                    else if (detail.Parameter.ParameterName == "出站日期")//产出日期须检验员填写
                                    {
                                        <DateTimePicker TValue="DateTime?" @bind-Value="@detail.Record.DateTimeValue" IsDisabled="@(!(_IsInspector()))" />

                                    }
                                    //具有选择性输入
                                    else if (!string.IsNullOrWhiteSpace(detail.Parameter.Category) && detail.Parameter.ParameterType == ParameterType.String)
                                    {
                                        //获得候选字串集合
                                        List<SelectedItem> items = new List<SelectedItem>();
                                        items.Add(new SelectedItem(null, "未录入"));
                                        try
                                        {
                                            var candidates = Db.CandidateLists.Where(x => x.Category == detail.Parameter.Category).Select(x => x.Candidate).OrderBy(x => x).ToList();
                                            if (candidates != null && candidates.Count > 0)
                                            {
                                                foreach (var c in candidates)
                                                {
                                                    items.Add(new SelectedItem(c, c));
                                                }
                                            }
                                        }
                                        catch (Exception ex)
                                        {

                                        }

                                        if (detail.Parameter.IsMulti)
                                        {
                                            if (string.IsNullOrWhiteSpace(detail.Record.StringValue))
                                            {
                                                detail.Record.StringValue = null;
                                            }
                                            if (_ValidateSelect(detail.Record.StringValue, items, true))
                                            {
                                                <MultiSelect Color="Color.Success" @bind-Items="@items" @bind-Value="@detail.Record.StringValue"  @key="detail.Record.StringValue"/>
                                            }
                                            else
                                            {
                                                <BootstrapInput @bind-Value="@detail.Record.StringValue" />
                                            }
                                        }
                                        else
                                        {
                                            if (string.IsNullOrWhiteSpace(detail.Record.StringValue))
                                            {
                                                detail.Record.StringValue = null;
                                            }

                                            if (_ValidateSelect(detail.Record.StringValue, items, false))
                                            {
                                                <Select Color="Color.Success" @bind-Items="@items" @bind-Value="@detail.Record.StringValue" />
                                            }
                                            else
                                            {
                                                <BootstrapInput @bind-Value="@detail.Record.StringValue" />
                                            }
                                        }

                                    }
                                    //
                                    else if (detail.Parameter.ParameterType == ParameterType.Date)
                                    {
                                        <DateTimePicker TValue="DateTime?" @bind-Value="detail.Record.DateTimeValue" />
                                    }
                                    else if (detail.Parameter.ParameterType == ParameterType.Time)
                                    {
                                        <DateTimePicker TValue="DateTime?" ViewModel="DatePickerViewModel.DateTime" @bind-Value="detail.Record.DateTimeValue" />
                                    }
                                    else if (detail.Parameter.ParameterType == ParameterType.Number)
                                    {
                                        <BootstrapInput @bind-Value="@detail.Record.NumberValue" />
                                    }
                                    else
                                    {
                                        <BootstrapInput @bind-Value="@detail.Record.StringValue" />
                                    }
                                </div>
                            </td>

                            <td><span class="m-2">@detail.Parameter.ParameterUnit</span></td>
                            @if (detail.Parameter.IsCheckPoint)
                            {
                                //检验标准
                                if (!string.IsNullOrWhiteSpace(detail.Parameter.StandardString))
                                {
                                    <td><div class="m-2">@detail.Parameter.StandardString</div></td>
                                }
                                else
                                {
                                    string sp1, sp2;
                                    if (detail.Parameter.StandardLineBottom == null)
                                    {
                                        sp1 = "不限";
                                    }
                                    else
                                    {
                                        sp1 = detail.Parameter.StandardLineBottom.Value.ToString();
                                    }

                                    if (detail.Parameter.StandardLineTop == null)
                                    {
                                        sp2 = "不限";
                                    }
                                    else
                                    {
                                        sp2 = detail.Parameter.StandardLineTop.Value.ToString();
                                    }
                                    <td><span class="m-2">@($"[ {sp1} , {sp2} ]")</span></td>
                                }

                                //合格率
                                //检验员
                                //质量状态
                                //合格率
                                bool notInspector = !(_IsInspector());
                                <td>
                                    <div class="m-2">

                                        <BootstrapInput FormatString="N2" step="1" placeholder="请输入合格率" @bind-Value="@detail.Record.CheckResult" IsDisabled="@notInspector" />

                                    </div>
                                </td>

                                //检验员
                                <td>
                                    <div class="m-2">
                                        @{
                                            if (string.IsNullOrWhiteSpace(detail.Record.Inspector))
                                            {
                                                detail.Record.Inspector = null;
                                            }

                                            if (_ValidateSelect(detail.Record.Inspector, Inspectors, false))
                                            {
                                                <Select Color="Color.Success" @bind-Items="@Inspectors" @bind-Value="@detail.Record.Inspector" IsDisabled="@notInspector" />
                                            }
                                            else
                                            {
                                                <BootstrapInput placeholder="请选择检验员" @bind-Value="@detail.Record.Inspector" IsDisabled="@notInspector" />
                                            }
                                        }

                                    </div>
                                </td>

                                            //质量状态
                                <td>
                                    <div class="m-2">
                                        <span>
                                            @{
                                                if (string.IsNullOrWhiteSpace(detail.Record.QualityState))
                                                {
                                                    detail.Record.QualityState = null;
                                                }

                                                if (_ValidateSelect(detail.Record.QualityState, QualityStates, false))
                                                {
                                                    <Select Color="Color.Success" @bind-Items="@QualityStates" @bind-Value="@detail.Record.QualityState" IsDisabled="@notInspector" />
                                                }
                                                else
                                                {
                                                    <BootstrapInput placeholder="请选择质量状态" @bind-Value="@detail.Record.QualityState" IsDisabled="@notInspector" />
                                                }
                                            }
                                        </span>

                                    </div>
                                </td>



                            }
                            else
                            {
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                            }


                        </tr>
                    }
                </tbody>


            </table>

        </div>

    }


</div>
    
    @code {

    






        List<SelectedItem> Inspectors
        {
            get
            {
                if (_Inspectors == null)
                {
                    _Inspectors = new List<SelectedItem>();
                    _Inspectors.Add(new SelectedItem(null, "未检"));
                    //_Inspectors.Add(new SelectedItem("未检", "未检"));
                    foreach (var x in Db.CandidateLists.Where(x => x.Category == "检验员").Select(x => x.Candidate))
                    {
                        var item = new SelectedItem(x, x);
                        _Inspectors.Add(item);
                    }
                }
                return _Inspectors;
            }
            set
            {
                _Inspectors = value;
            }
        }
        List<SelectedItem> _Inspectors = null;

        List<SelectedItem> QualityStates
        {
            get
            {
                if (_QualityStates == null)
                {
                    _QualityStates = new List<SelectedItem>();
                    _QualityStates.Add(new SelectedItem(null, "未处理"));

                    foreach (var x in Db.CandidateLists.Where(x => x.Category == "质量状态").Select(x => x.Candidate))
                    {
                        var item = new SelectedItem(x, x);
                        _QualityStates.Add(item);
                    }
                }
                return _QualityStates;
            }
            set
            {
                _QualityStates = value;
            }
        }
        List<SelectedItem> _QualityStates = null;

        List<SelectedItem> InputLots { get; set; }




        [Parameter]
        public List<ProcessBase.Models.ProcessDetail> ProcessDetails
        {
            get
            {
                return _ProcessDetails;
            }
            set
            {
                _ProcessDetails = value;
                _MakeInputLots();
            }
        }
        List<ProcessBase.Models.ProcessDetail> _ProcessDetails = null;







        public void SaveRecord()
        {


            if (_IsEditor())
            {


                string error = Helpers.ProcessRecordSaveHelper.Save(ProcessDetails);

                if (string.IsNullOrEmpty(error))
                {
                    MessageService?.Show(new MessageOption()
                    {
                        Content = $"保存记录成功。",
                        Icon = "fa fa-info-circle",
                        ShowDismiss = true,
                        Color = Color.Success
                    });
                }
                else
                {
                    MessageService?.Show(new MessageOption()
                    {
                        Content = $"发生错误：{error}。",
                        Icon = "fa fa-info-circle",
                        ShowDismiss = true,
                        Color = Color.Danger
                    });
                }


            }
            else
            {
                MessageService?.Show(new MessageOption()
                {
                    Content = $"发生错误：你登录的角色没有修改数据的权限。",
                    Icon = "fa fa-info-circle",
                    ShowDismiss = true,
                    Color = Color.Danger
                });
            }
        }




        bool _IsEditor()
        {
            return Helpers.UserHelper.HasRole(user, "录入员");
        }

        bool _IsInspector()
        {
            return Helpers.UserHelper.HasRole(user, "检验员");
        }

        void _MakeInputLots()
        {
            InputLots = new List<SelectedItem>();
            InputLots.Add(new SelectedItem(null, "未输入"));
            if (_ProcessDetails == null || _ProcessDetails.Count <= 0)
            {
                return;
            }



            var process = _ProcessDetails[0].Parameter.ProcessName;
            var mainLotNo = _ProcessDetails.Where(x => x.Record.ParameterName == "主批号").Select(x => x.Record.StringValue).FirstOrDefault();

            var queryInputProcesses = Db.ProcessInputOutputs.Where(x => x.OutputProcessName == process).Select(x => x.InputProcessName);
            List<string> outputLots = new List<string>();
            foreach (var inputProcessName in queryInputProcesses)
            {

                var query = Db.ProcessStatistics.Where(x => x.ProcessName == inputProcessName&&x.MainLotNo==mainLotNo && x.ProcessState.Contains("已出站") && x.QualityState.Contains("流通")).Select(x => x.LotNoOutput);

                if (query.Count() > 0)
                {
                    query = query.OrderBy(x => x);

                    foreach (var lot in query)
                    {
                        InputLots.Add(new SelectedItem(lot, lot));
                    }
                }

            }



        }

        bool _ValidateSelect(string str, List<SelectedItem> items, bool isMulti)
        {

            if (items == null || items.Count <= 0)
            {
                return false;
            }

            if (str == null)
            {
                return true;
            }

            if (string.IsNullOrWhiteSpace(str))
            {
                return false;
            }

            if (isMulti)
            {
                string[] strs = str.Split(new char[] { ',' });
                foreach (var s in strs)
                {
                    if (items.Select(x => x.Value).Where(x => x == s).FirstOrDefault() == null)
                    {
                        return false;
                    }
                }
            }
            else
            {
                if (items.Select(x => x.Value).Where(x => x == str).FirstOrDefault() == null)
                {
                    return false;
                }
            }


            return true;

        }


        string user { get; set; }
        protected override async Task OnInitializedAsync()
        {
            //user = await Helpers.UserHelper.GetUserName();


            var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
            var User = authState.User;

            user = UserManager.GetUserId(User);

        }
    }

